package com.iot.protocol;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class TcpServer implements AutoCloseable {
    private final int port;
    private final ServerSocket serverSocket;
    private final ExecutorService executorService;
    private volatile boolean running;

    public TcpServer(int port) throws IOException {
        this.port = port;
        this.serverSocket = new ServerSocket(port);
        this.executorService = Executors.newCachedThreadPool();
        this.running = true;
        log.info("TCP服务器已启动，监听端口: {}", port);
    }

    public void start() {
        try {
            while (running) {
                Socket clientSocket = serverSocket.accept();
                log.info("新的客户端连接: {}", clientSocket.getRemoteSocketAddress());
                executorService.execute(new ClientHandler(clientSocket));
            }
        } catch (IOException e) {
            if (running) {
                log.error("服务器发生错误: {}", e.getMessage(), e);
            }
        }
    }

    @Override
    public void close() {
        running = false;
        executorService.shutdown();
        try {
            if (serverSocket != null && !serverSocket.isClosed()) {
                serverSocket.close();
            }
        } catch (IOException e) {
            log.error("关闭服务器时发生错误: {}", e.getMessage(), e);
        }
        log.info("TCP服务器已关闭");
    }

    private class ClientHandler implements Runnable {
        private final Socket clientSocket;

        public ClientHandler(Socket socket) {
            this.clientSocket = socket;
        }

        @Override
        public void run() {
            try (BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), StandardCharsets.UTF_8));
                 PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
                
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    log.info("收到客户端消息: {}", inputLine);
                    // 发送响应
                    String response = "服务器已收到消息: " + inputLine;
                    out.println(response);
                }
            } catch (IOException e) {
                log.error("处理客户端连接时发生错误: {}", e.getMessage(), e);
            } finally {
                try {
                    clientSocket.close();
                } catch (IOException e) {
                    log.error("关闭客户端连接时发生错误: {}", e.getMessage(), e);
                }
            }
        }
    }

    public static void main(String[] args) {
        int port = 8888; // 默认端口

        try (TcpServer server = new TcpServer(port)) {
            server.start();
        } catch (IOException e) {
            log.error("启动服务器失败: {}", e.getMessage(), e);
        }
    }
} 